package main

import (
    "fmt"
    "sync"
    "time"
)

type Resource struct {
    data int
    rwLock sync.RWMutex
}

func (r *Resource) readData() int {
    r.rwLock.RLock()
    defer r.rwLock.RUnlock()
    return r.data
}

func (r *Resource) writeData(newData int) {
    r.rwLock.Lock()
    defer r.rwLock.Unlock()
    r.data = newData
}

func main() {
    resource := Resource{data: 0}

    // 多个协程同时读取数据
    for i := 0; i < 5; i++ {
        go func(id int) {
            fmt.Printf("Reader %d read data: %d\n", id, resource.readData())
        }(i)
    }

    // 写入数据的协程
    go func() {
        //time.Sleep(1 * time.Second)
        resource.writeData(42)
        fmt.Println("Data written.")
    }()
	

    time.Sleep(2 * time.Second)
}